angular.module('inspinia', ['angularFileUpload']).controller('wechatPublicBatchCtrl', function ($scope, $http, SweetAlert, $state, $stateParams, i18nService, $timeout, FileUploader) {
  //数据源
  i18nService.setCurrentLang('zh-cn');


  $scope.titles = [{value: "", text: "请选择"}];
  $scope.pubNames = [{value: "", text: "请选择"}];
  $scope.userType = angular.copy(initData.MSG_TO_USER_TYPE);
  $scope.userType.unshift({value: "", text: "请选择"});

  // 重置按钮
  $scope.resetForm = function () {
    $scope.info = {title: "", userType: "", pubAcc: "", endReplyTimeBegin: "", endReplyTimeEnd: ""};
  };
  $scope.resetForm();


  // 查询分页
  $scope.paginationOptions = angular.copy($scope.paginationOptions);
  $scope.wetchatPublicBatchGrid = {
    paginationPageSize: 10,                  //分页数量
    paginationPageSizes: [10, 20, 50, 100],	  //切换每页记录数
    useExternalPagination: true,		  //开启拓展名
    enableHorizontalScrollbar: true,        //横向滚动条
    enableVerticalScrollbar: true,  		//纵向滚动条
    columnDefs: [
      {field: 'id', displayName: '序号', pinnable: false, width: 120, sortable: false},
      {field: 'title', displayName: '模板标题', pinnable: false, width: 280, sortable: false},
      {field: 'pubName', displayName: '公众号', pinnable: false, width: 180, sortable: false},
      {field: 'userTypeName', displayName: '下发对象', pinnable: false, width: 180, sortable: false},
      {
        field: 'pushTime',
        displayName: '下发时间',
        pinnable: false,
        width: 150,
        sortable: false,
        cellFilter: 'date:"yyyy-MM-dd HH:mm:ss"'
      },
      {field: 'timeBlock', displayName: '发送时间段', pinnable: false, width: 300, sortable: false},
      {field: 'pushStatusName', displayName: '下发状态', pinnable: false, width: 180, sortable: false},
      {field: 'send', displayName: '发送成功人数', pinnable: false, width: 180, sortable: false},
      {field: 'notSend', displayName: '未发送成功人数', pinnable: false, width: 180, sortable: false},
      {field: 'operator', displayName: '操作人', pinnable: false, width: 180, sortable: false},
      {
        field: 'action',
        displayName: '操作',
        width: 250,
        pinnedRight: true,
        sortable: false,
        editable: true,
        cellTemplate:
          '<div class="lh30">'
          + '<a class="lh30" ng-show="(row.entity.pushStatus ==\'STOP\' || row.entity.pushStatus ==\'COMPLETE\') && grid.appScope.hasPermit(\'publicAccountMsgBatch.delete\')" ng-click="grid.appScope.del(row.entity.pushBatchNo)"   >删除</a>'
          + '<a class="lh30" ng-show="row.entity.pushStatus ==\'SENDING\' && grid.appScope.hasPermit(\'publicAccountMsgBatch.suspend\')" ng-click="grid.appScope.updatePushStatus(row.entity.id,1)" > | 暂停发送</a>'
          + '<a class="lh30" ng-show="(row.entity.pushStatus ==\'SUSPEND\' || row.entity.pushStatus ==\'WAIT\') && grid.appScope.hasPermit(\'publicAccountMsgBatch.start\')" ng-click="grid.appScope.updatePushStatus(row.entity.id,2)" > | 继续发送</a>'
          + '<a class="lh30" ng-show="(row.entity.pushStatus ==\'SUSPEND\' || row.entity.pushStatus ==\'WAIT\') && grid.appScope.hasPermit(\'publicAccountMsgBatch.updateTimeBlock\')" ui-sref="sys.wechatPublicBatchEdit({id:row.entity.id})" > | 修改</a>'
          + '<a class="lh30" ng-show="(row.entity.pushStatus ==\'SUSPEND\' || row.entity.pushStatus ==\'WAIT\') && grid.appScope.hasPermit(\'publicAccountMsgBatch.stop\')" ng-click="grid.appScope.updatePushStatus(row.entity.id,3)" > | 终止</a>'
          + '</div>'
      }
    ],
    onRegisterApi: function (gridApi) {
      $scope.gridApi = gridApi;
      $scope.gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
        $scope.paginationOptions.pageNo = newPage;
        $scope.paginationOptions.pageSize = pageSize;
        $scope.query();
      });
    }
  };

  // 查询按钮
  $scope.query = function () {
    if ($scope.loadImg) {
      return;
    }
    $scope.loadImg = true;
    $http.post('publicAccountMsgBatch/list',
      "info=" + angular.toJson($scope.info) + "&pageNo=" + $scope.paginationOptions.pageNo + "&pageSize=" +
      $scope.paginationOptions.pageSize, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
      .success(function (result) {
        if (result.status) {
          $scope.wetchatPublicBatchGrid.data = result.page.result;
          $scope.wetchatPublicBatchGrid.totalItems = result.page.totalCount;
        } else {
          $scope.notice(result.msg);
        }
        $scope.loadImg = false;
      }).error(function () {
      $scope.notice("系统异常！");
    });
  };

  $scope.query();


  /***
   * 获取列表查询条件
   */
  $scope.queryCondition = function () {
    $http.post('publicAccountMsgTemp/queryCondition',
      null, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
      .success(function (result) {
        if (result.status) {
          if (result.data.titles && result.data.titles.length > 0) {
            result.data.titles.forEach(data => {
              $scope.titles.push({value: data.title, text: data.title});
            })

          }
          if (result.data.pubNames && result.data.pubNames.length > 0) {
            result.data.pubNames.forEach(data => {
              $scope.pubNames.push({value: data.pubAcc, text: data.pubName});
            })
          }
        } else {
          $scope.notice(result.msg);
        }
      }).error(function () {
      $scope.notice("系统异常！");
    });
  };

  $scope.queryCondition();


  /**
   * 提交公众号模板消息推送批次记录表
   */
  $scope.submitBatchInfo = function () {
    $scope.hideSendModal();
    $scope.submitting = true;
    $scope.batchInfo.tempId = $scope.detailInfo.id;
    $http({
      url: 'publicAccountMsgBatch/save',
      method: 'POST',
      data: {info: $scope.batchInfo}
    }).success(function (result) {
      if (result.status) {
        $scope.submitting = false;
        $state.transitionTo('workOrder.workOrderManager', null, {reload: false});
        $scope.notice(result.msg);
      } else {
        $scope.submitting = false;
        $scope.notice(result.msg);
      }
    });
  };

  $scope.del = function (pushBatchNo) {
    SweetAlert.swal({
        title: "确定删除？",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnConfirm: true,
        closeOnCancel: true
      },
      function (isConfirm) {
        if (isConfirm) {
          $http({
            url: 'publicAccountMsgBatch/delete?pushBatchNo=' + pushBatchNo,
            method: 'get'
          }).success(function (result) {
            if (result.status) {
              $scope.query();
            }
            $scope.notice(result.msg);
          });
        }
      });
  };


  $scope.updatePushStatus = function (id, operate) {
    var title = "";
    var url = "";
    if (operate == 1) {
      title = "确定暂停？";
      url = "suspend";
    } else if (operate == 2) {
      title = "确定继续发送？";
      url = "start";
    } else if (operate == 3) {
      title = "是否确定终止发送？";
      url = "stop";
    }
    SweetAlert.swal({
        title: title,
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnConfirm: true,
        closeOnCancel: true
      },
      function (isConfirm) {
        if (isConfirm) {
          $http({
            url: 'publicAccountMsgBatch/' + url + "?id=" + id,
            method: 'get'
          }).success(function (result) {
            if (result.status) {
              $scope.query();
            }
            $scope.notice(result.msg);
          });
        }
      });
  }


});


